package com.cmict.data.infra.utils;

import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;

import java.io.StringWriter;

/**
 * created by liutao 2021/11/7.
 */
@Slf4j
public class FreeMarkerUtil {

    private static String defaultCharacter = "UTF-8";
    private static Configuration cfg;

    static {
        cfg = new Configuration(Configuration.VERSION_2_3_30);
        cfg.setDefaultEncoding(defaultCharacter);
        cfg.setTagSyntax(Configuration.AUTO_DETECT_TAG_SYNTAX);
    }

    private FreeMarkerUtil() {

    }

    public static String process(String templateText, Object map) {
        String result = null;
        String name = "template";
        try {
            StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
            stringTemplateLoader.putTemplate(name, templateText);
            cfg.setTemplateLoader(stringTemplateLoader);
            Template template = cfg.getTemplate(name, defaultCharacter);
            StringWriter out = new StringWriter();
            template.process(map, out);
            out.flush();
            result = out.toString();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

}
